﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Scheduler;
using System.Windows.Media;

//modello app
using Angerona.Model;

//PhotoChooser
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Phone;
using System.IO;

namespace Angerona.Views
{
    public partial class ModCar : PhoneApplicationPage
    {
        PhotoChooserTask photoChooserTask = new PhotoChooserTask();
        string nameOfImage;
        DateTime defaultDate = new DateTime(2013, 1, 1);
        Boolean userWantToChangePic = false;
        
        public ModCar()
        {
            InitializeComponent();

            this.carfuel.ItemsSource = new List<String>() { AngeronaLang.fuelgasoline, AngeronaLang.fueldiesel, AngeronaLang.fuelgpl, AngeronaLang.fuelelectric };

            this.carboughtdate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.carproductiondate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.assurancedate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.bollodate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            this.revisiondate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);

            ApplicationBarInitializer();
            ReadData();
        }


        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // save button
            ApplicationBarIconButton btn_save = new ApplicationBarIconButton();
            btn_save.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_save.Text = AngeronaLang.save;
            ApplicationBar.Buttons.Add(btn_save);
            btn_save.Click += new EventHandler(btn_save_Click);

            // undo button
            ApplicationBarIconButton btn_undo = new ApplicationBarIconButton();
            btn_undo.IconUri = new Uri("/Img/appbar_cancel.png", UriKind.Relative);
            btn_undo.Text = AngeronaLang.undo;
            ApplicationBar.Buttons.Add(btn_undo);
            btn_undo.Click += new EventHandler(btn_undo_Click);
        }

        private void btn_undo_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void ReadData()
        {
            VehiclesTable Vehicle;
            var v = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (v == Visibility.Visible)
            {
                Uri invertedColorImage = new Uri("/Img/AppIcons/pictureAdd_100_100_INV.png", UriKind.Relative);
                ImageSource sourceOfImageInverted = new BitmapImage(invertedColorImage);
                imageOfTheCar.Source = sourceOfImageInverted;
            }
            carname.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carmanufacter.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carmodel.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carfuel.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carhorse.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carkw.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carvolume.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carplate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carserial.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carboughtdate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carproductiondate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carinitialkm.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            cartraveledkm.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            assurancecompany.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            assurancenumber.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            assurancedate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            bollodate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            revisiondate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            if (IsolatedStorageSettings.ApplicationSettings.Contains("AutoCliccked"))
            {
                int ID = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string);
                Vehicle = App.ViewModel.getElementWithID(ID);

                // Check If ImageOfCar exists
                if (Vehicle.ImageOfCar != null)
                {
                    BitmapImage bi = new BitmapImage();
                    using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream imageFileStream = myIsoStore.OpenFile(Vehicle.ImageOfCar, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            bi.SetSource(imageFileStream);
                            imageFileStream.Close();
                        }
                        imageOfTheCar.Source = bi;
                    }
                }

                carname.Text = Vehicle.VehicleName;
                carmanufacter.Text = Vehicle.Manufacter;
                carmodel.Text = Vehicle.VehicleModel;
                
                carfuel.SelectedItem = Vehicle.FuelType;

                carhorse.Text = Vehicle.HorsePower;
                carkw.Text = Vehicle.KwPower;
                carvolume.Text = Vehicle.EngineCapacity;
                carplate.Text = Vehicle.PlateNumber;
                carserial.Text = Vehicle.SerialNumber;
                carboughtdate.Value = Vehicle.PurchasedDate;
                carproductiondate.Value = Vehicle.ProductionDate;
                carinitialkm.Text = Vehicle.PurchasedKm;
                cartraveledkm.Text = Vehicle.TraveledKm;
                assurancecompany.Text = Vehicle.AssuranceCompany;
                assurancenumber.Text = Vehicle.AssuranceNumber;
                assurancedate.Value = Vehicle.AssuranceDate;
                bollodate.Value = Vehicle.Bollo;
                revisiondate.Value = Vehicle.Revision;
            }
        }

        // Salvataggio dei dati all'interno del database.
        private void btn_save_Click(object sender, EventArgs e)
        {

            // Controllo l'id della vettura.
            if (IsolatedStorageSettings.ApplicationSettings.Contains("AutoCliccked"))
            {
                VehiclesTable Vehicle;
                int ID = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string);
                Vehicle = App.ViewModel.getElementWithID(ID);

                if (carname.Text.Length == 0)
                {
                    MessageBox.Show(AngeronaLang.addcarerror);
                }
                else
                {
                    //checking for name already in using
                    int i = 0;
                    bool samename = false;
                    int idmax = App.ViewModel.getNumbersOfVehicles();
                    List<int> idlist = App.ViewModel.getVehicleIdlist();
                    while (i < idmax)
                    {
                        if (idlist[i] != ID)
                        {
                            VehiclesTable temp = App.ViewModel.getElementWithID(idlist[i]);
                            if (carname.Text == temp.VehicleName)
                            {
                                samename = true;
                                MessageBox.Show(AngeronaLang.nameAlreadyUsed);
                                break;
                            }
                        }
                        i++;
                    }
                    if (!samename)
                    {
                        // Controllo se l'utente ha premuto sulla foto della vettura. Se true, allora devo sostituirla,
                        // se false, mantengo quella precedente.
                        if (userWantToChangePic)
                        {
                            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                if (myIsolatedStorage.FileExists(Vehicle.ImageOfCar))
                                {
                                    myIsolatedStorage.DeleteFile(Vehicle.ImageOfCar);
                                }
                                Vehicle.ImageOfCar = nameOfImage;
                            }
                        }
                        Vehicle.VehicleName = carname.Text;
                        Vehicle.Manufacter = carmanufacter.Text;
                        Vehicle.VehicleModel = carmodel.Text;
                        Vehicle.FuelType = carfuel.SelectedItem.ToString();
                        Vehicle.KwPower = carkw.Text;
                        Vehicle.HorsePower = carhorse.Text;
                        Vehicle.EngineCapacity = carvolume.Text;
                        Vehicle.PlateNumber = carplate.Text;
                        Vehicle.SerialNumber = carserial.Text;
                        Vehicle.ProductionDate = (DateTime)carproductiondate.Value;
                        Vehicle.PurchasedDate = (DateTime)carboughtdate.Value;
                        Vehicle.PurchasedKm = carinitialkm.Text;
                        Vehicle.TraveledKm = cartraveledkm.Text;
                        Vehicle.AssuranceCompany = assurancecompany.Text;
                        Vehicle.AssuranceDate = (DateTime)assurancedate.Value;
                        Vehicle.AssuranceNumber = assurancenumber.Text;
                        Vehicle.Bollo = (DateTime)bollodate.Value;
                        Vehicle.Revision = (DateTime)revisiondate.Value;

                        SetReminders(Vehicle);
                        NavigationService.GoBack();
                    }
                }
            }
        }

        private void SetReminders(VehiclesTable VehicleToBeSetted)
        {
            //Reminder for Assurance expiration
            if (VehicleToBeSetted.AssuranceDate != defaultDate)
            {
                DateTime AssuranceDate = (DateTime)VehicleToBeSetted.AssuranceDate;

                ScheduledAction OldReminder = ScheduledActionService.Find("AssuranceDate" + VehicleToBeSetted.VehicleName);
                if (OldReminder != null)
                    ScheduledActionService.Remove(OldReminder.Name);

                //Create the reminder
                Reminder AssuranceDateReminder = new Reminder("AssuranceDate" + VehicleToBeSetted.VehicleName)
                {
                    BeginTime = AssuranceDate.AddHours(9),
                    Title = AngeronaLang.assuranceReminderTitle,
                    Content = VehicleToBeSetted.VehicleName + ": " + AngeronaLang.assuranceReminderContenent,
                    //when a user interact with the reminder the App will open on User view
                    NavigationUri = new Uri("/Views/Vehicles.xaml", UriKind.Relative),

                };
                ScheduledActionService.Add(AssuranceDateReminder);
            }

            //Reminder for Bollo expiration
            if (VehicleToBeSetted.Bollo != defaultDate)
            {
                DateTime Bollo = (DateTime)VehicleToBeSetted.Bollo;

                ScheduledAction OldReminder = ScheduledActionService.Find("Bollo" + VehicleToBeSetted.VehicleName);
                if (OldReminder != null)
                    ScheduledActionService.Remove(OldReminder.Name);

                //Create the reminder
                Reminder BolloReminder = new Reminder("Bollo" + VehicleToBeSetted.VehicleName)
                {
                    BeginTime = Bollo.AddHours(9),
                    Title = AngeronaLang.bolloReminderTitle,
                    Content = VehicleToBeSetted.VehicleName + ": " + AngeronaLang.bolloReminderContenent,
                    //when a user interact with the reminder the App will open on User view
                    NavigationUri = new Uri("/Views/Vehicles.xaml", UriKind.Relative),

                };
                ScheduledActionService.Add(BolloReminder);
            }

            //Reminder for Revision expiration
            if (VehicleToBeSetted.Revision != defaultDate)
            {
                DateTime Revision = (DateTime)VehicleToBeSetted.Revision;

                ScheduledAction OldReminder = ScheduledActionService.Find("Revision" + VehicleToBeSetted.VehicleName);
                if (OldReminder != null)
                    ScheduledActionService.Remove(OldReminder.Name);

                //Create the reminder
                Reminder RevisionReminder = new Reminder("Revision" + VehicleToBeSetted.VehicleName)
                {
                    BeginTime = Revision.AddHours(9),
                    Title = AngeronaLang.revisionReminderTitle,
                    Content = VehicleToBeSetted.VehicleName + ": " + AngeronaLang.revisionReminderContenent,
                    //when a user interact with the reminder the App will open on User view
                    NavigationUri = new Uri("/Views/Vehicles.xaml", UriKind.Relative),

                };
                ScheduledActionService.Add(RevisionReminder);
            }
        }

        private void picker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DatePicker dp = (DatePicker)sender;
            dp.Value = CheckAgeOrDefault((DateTime)dp.Value);
            if (dp.Name == "assurancedate" | dp.Name == "bollodate" | dp.Name == "revisiondate")
                if (dp.Value < DateTime.Now & dp.Value != defaultDate)
                {
                    dp.Value = defaultDate;
                    MessageBox.Show(AngeronaLang.ReminderErrorDate, AngeronaLang.Error, MessageBoxButton.OK);
                }
            sender = dp;
        }

        private DateTime CheckAgeOrDefault(DateTime x)
        {
            DateTime temp = new DateTime(1754, 1, 1);
            if (x < temp)
            {
                MessageBox.Show(AngeronaLang.ReminderToOldDate, AngeronaLang.Error, MessageBoxButton.OK);
                x = new DateTime(2013, 1, 1);
            }
            return x;
        }


        // Controlla se il nome della vettura è univoco, in caso negativo, mostra un MessageBox contenente l'errore.
        private void carname_LostFocus(object sender, RoutedEventArgs e)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("AutoCliccked"))
            {
                int ID = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string);
                int i = 0;
                //bool samename = false;
                int idmax = App.ViewModel.getNumbersOfVehicles();
                List<int> idlist = App.ViewModel.getVehicleIdlist();
                while (i < idmax)
                {
                    if (idlist[i] != ID)
                    {
                        VehiclesTable temp = App.ViewModel.getElementWithID(idlist[i]);
                        if (carname.Text == temp.VehicleName)
                        {
                            //samename = true;
                            MessageBox.Show(AngeronaLang.nameAlreadyUsed);
                            break;
                        }
                    }
                    i++;
                }
            }
        }

        //
        // Metodi per la gestione del veicolo.

        // Start the photochooserTask
        private void imageOfCar_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            photoChooserTask.PixelHeight = 200;
            photoChooserTask.PixelWidth = 400;
            photoChooserTask.Completed += new EventHandler<PhotoResult>(taskToChoosePhoto_Completed);
            photoChooserTask.Show();
        }

        //
        // Selezione della foto completata.
        // 
        public void taskToChoosePhoto_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                // Impostato a true per controllare il salvataggio
                userWantToChangePic = true;
                BitmapImage image = new BitmapImage();
                MemoryStream ms = new MemoryStream();
                image.SetSource(e.ChosenPhoto);
                DateTime time = DateTime.Now;
                nameOfImage = time.Millisecond.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString();

                WriteableBitmap writeableImage = new WriteableBitmap(image);

                // Select the image for xaml
                imageOfTheCar.Source = writeableImage;

                // Writes the image as jpeg inside the stream MemoryStream ms
                writeableImage.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);

                // Saving image into isolatedStorage
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Nome dell'immagine = tempo 
                    IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(nameOfImage);
                    Extensions.SaveJpeg(writeableImage, fileStream, writeableImage.PixelWidth, writeableImage.PixelHeight, 0, 100);
                    fileStream.Close();
                }
            }
        }
    }
}